package com.zhiwei.common.service.impl;

import com.zhiwei.common.service.CacheService;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;

/**
 * function 默认缓存服务实现
 * author zhiwei.yang
 * time 2020-2-29-9:24
 */
public class DefaultCacheServiceImpl implements CacheService {

    /** spring 线程安全缓存管理器 **/
    private ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager();

    public DefaultCacheServiceImpl(){
        //允许空值: 应用于单值场景
        cacheManager.setAllowNullValues(true);
        cacheManager.setStoreByValue(true); //值传递，防止应用传递业务层更新直接同步缓存
    }

    @Override
    public void putCacheObject(String cacheGroupName, Object key, Object value) {
        //getCache: 底层做了同步控制，缓存存在则返回，不存在则创建后返回
        cacheManager.getCache(cacheGroupName).put(key, value);
    }

    @Override
    public Object getCacheObject(String cacheGroupName, Object key) {
        if (null == cacheManager.getCache(cacheGroupName).get(key)) {
            return null;
        }
        return cacheManager.getCache(cacheGroupName).get(key).get();
    }

    @Override
    public boolean isExistCacheKey(String cacheGroupName, Object key) {
        ConcurrentMapCache concurrentMapCache = (ConcurrentMapCache) cacheManager.getCache(cacheGroupName);
        return concurrentMapCache.getNativeCache().containsKey(key);
    }

    @Override
    public void removeCacheGroup(String cacheGroupName) {
        cacheManager.getCache(cacheGroupName).clear();
    }

    @Override
    public void removeCacheObject(String cacheGroupName, String key) {
        cacheManager.getCache(cacheGroupName).evict(key);
    }
}
